package com.example.knowledgeget1.GraphDBCommon.Repository;

import com.example.knowledgeget1.GraphDBCommon.Entity.Node;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface NodeRepository extends Neo4jRepository<Node, Long> {
    Node findByName(String name);
    //添加pre联系
    @Query("MATCH (a:Node), (b:Node) WHERE a.name = $nodeNameA AND b.name = $nodeNameB CREATE (a)-[:PreRelationship]->(b) ")
    void addPreRelationshipByName(@Param("nodeNameA") String nodeNameA, @Param("nodeNameB") String nodeNameB);
    //删除pre联系
    @Query("MATCH (a:Node {name: $nodeNameA})-[r:PreRelationship]->(b:Node {name: $nodeNameB}) DELETE r")
    void deletePreRelationshipByName(@Param("nodeNameA") String nodeNameA, @Param("nodeNameB") String nodeNameB);
    //添加general联系
    @Query("MATCH (a:Node), (b:Node) WHERE a.name = $nodeNameA AND b.name = $nodeNameB CREATE (a)-[:GeneralRelationship]->(b) ")
    void addGeneralRelationshipByName(@Param("nodeNameA") String nodeNameA, @Param("nodeNameB") String nodeNameB);
    //删除general联系
    @Query("MATCH (a:Node {name: $nodeNameA})-[r:GeneralRelationship]->(b:Node {name: $nodeNameB}) DELETE r")
    void deleteGeneralRelationshipByName(@Param("nodeNameA") String nodeNameA, @Param("nodeNameB") String nodeNameB);
    //查询pre联系
    @Query("MATCH (a:Node {name: $nodeNameA}), (b:Node {name: $nodeNameB}) " +
            "WHERE EXISTS((a)-[:PreRelationship]->(b)) " +
            "RETURN true AS exists " +
            "UNION " +
            "MATCH (a:Node {name: $nodeNameA}), (b:Node {name: $nodeNameB}) " +
            "WHERE NOT EXISTS((a)-[:PreRelationship]->(b)) " +
            "RETURN false AS exists")
    boolean existsPreRelationship(@Param("nodeNameA") String nodeNameA, @Param("nodeNameB") String nodeNameB);
    //查询general联系
    @Query("MATCH (a:Node {name: $nodeNameA}), (b:Node {name: $nodeNameB}) " +
            "WHERE EXISTS((a)-[:GeneralRelationship]->(b)) " +
            "RETURN true AS exists " +
            "UNION " +
            "MATCH (a:Node {name: $nodeNameA}), (b:Node {name: $nodeNameB}) " +
            "WHERE NOT EXISTS((a)-[:GeneralRelationship]->(b)) " +
            "RETURN false AS exists")
    boolean existsGeneralRelationship(@Param("nodeNameA") String nodeNameA, @Param("nodeNameB") String nodeNameB);

    //查询数据库中Id最大的结点
    @Query("MATCH (n:Node) " +
            "RETURN n " +
            "ORDER BY n.id DESC " +
            "LIMIT 1")
    Node findNodeWithMaxNodeId();

    // 查找知识点的前置知识点
    @Query("MATCH (n:Node)-[:PreRelationship]->(p:Node) WHERE p.name = $name RETURN n.name")
    List<String> findPreKnowledgesByName(@Param("name") String name);

    // 查找知识点的后置知识点名称
    @Query("MATCH (n:Node)-[:PreRelationship]->(p:Node) WHERE n.name = $name RETURN p.name")
    List<String> findPostKnowledgeNamesByName(@Param("name") String name);
}